package com.budwk.app.sqfwV2.component;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.PersonInfo;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.PersonInfoService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfwV2.dto.dto.PersonInfoDTO;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.IocBean;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

@IocBean
@Slf4j
public class PersonInfoComponent {


    /**
     * 构建人员基本信息
     * @param reqVo
     */
    public static void checkPersonData(PersonInfoDTO reqVo) {
        // 初始化数据
        Sys_user user = CommonComponent.getCurrentUser();
        reqVo.setProvince(StringUtils.isNotEmpty(reqVo.getProvince()) ? reqVo.getProvince() : user.getProvince())
                .setCity(StringUtils.isNotEmpty(reqVo.getCity()) ? reqVo.getCity() : user.getCity())
                .setCommunity(StringUtils.isNotEmpty(reqVo.getCommunity()) ? reqVo.getCommunity() : user.getCommunity())
                .setCounty(StringUtils.isNotEmpty(reqVo.getCounty()) ? reqVo.getCounty() : user.getCounty())
                .setDistrict(StringUtils.isNotEmpty(reqVo.getDistrict()) ? reqVo.getDistrict() : user.getDistrict());
        String detailAddress = String.format("%s%s%s%s%s%s", reqVo.getProvince(), reqVo.getCity(), reqVo.getDistrict(),
                reqVo.getCounty(), reqVo.getCommunity(), StrUtil.formatStr(reqVo.getAddress()));
        reqVo.setDetailAddress(detailAddress);
        try {
            if (StringUtils.isNotEmpty(reqVo.getIdNumber())) {
                if (reqVo.getBirthDate() == null) {
                    DateTime birthDate = IdcardUtil.getBirthDate(reqVo.getIdNumber());
                    reqVo.setBirthDate(birthDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
                }
                if (reqVo.getAge() == null) {
                    reqVo.setAge(IdcardUtil.getAgeByIdCard(reqVo.getIdNumber()));
                }
                if (StringUtils.isEmpty(reqVo.getGender())) {
                    int gender = IdcardUtil.getGenderByIdCard(reqVo.getIdNumber());
                    String genderStr = "男";
                    genderStr = gender == 0 ? "女" : genderStr;
                    reqVo.setGender(genderStr);
                }
            }
        }catch (Exception e) {
            log.error("idcard error: ", e);
        }
        // 按照五级+身份证号检查用户是否存在
        PersonInfoService personInfoService = NutzIocUtils.getBean(PersonInfoService.class);
        PersonInfo personInfo = personInfoService.getPersonInfo(reqVo.getIdNumber());
        if (personInfo == null) {
            return;
        }
        if (StringUtils.isEmpty(reqVo.getId())) {
            throw new AppException("该地区已存在该用户，请勿重复添加！");
        }
        if (!reqVo.getId().equals(personInfo.getId())) {
            throw new AppException("该地区已存在该用户，请勿重复添加！");
        }
        PersonInfo personInfo1 = personInfoService.fetch(reqVo.getId());
        if (personInfo1 == null) {
            throw new AppException("用户不存在，请先新增用户");
        }
    }

    public static String getBusinessType(String oldBusinessType, String newBusinessType) {
        if (StringUtils.isEmpty(oldBusinessType)) {
            return newBusinessType;
        }
        if (!oldBusinessType.contains(newBusinessType)) {
            return oldBusinessType + "," + newBusinessType;
        }
        return newBusinessType;
    }

    /**
     * 构建提交时人员基本信息
     * @param reqVo
     */
    public static void buildPersonInfo(PersonInfoDTO reqVo) {
        if (SupportBusinessTypeEnum.CHILDREN_VISITATION.getName().equals(reqVo.getBusinessType())) {
            ChildrenVisitationComponent.assemblePerson(reqVo);
        }
        if (StringUtils.isEmpty(reqVo.getId())) {
            reqVo.setCreateBy(StringUtils.isEmpty(reqVo.getCreateBy()) ? SecurityUtil.getUserId() : reqVo.getCreateBy())
                    .setCreateDate(reqVo.getCreateDate() == null ? LocalDateTime.now() : reqVo.getCreateDate())
                    .setUpdateBy(StringUtils.isEmpty(reqVo.getUpdateBy()) ? SecurityUtil.getUserId() : reqVo.getUpdateBy())
                    .setUpdateDate(reqVo.getUpdateDate() == null ? LocalDateTime.now() : reqVo.getUpdateDate())
                    .setDeleted(false)
                    .setLatestStatus("正常");
            return;
        }
        reqVo.setUpdateBy(SecurityUtil.getUserId())
                .setUpdateDate(LocalDateTime.now())
                .setLatestStatus("正常");
    }

    public static void handlePersonData(PersonInfo personInfo) {
        PersonInfoService personInfoService = NutzIocUtils.getBean(PersonInfoService.class);
        SqfwFormsummaryNewService sqfwFormsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);
        if (StringUtils.isEmpty(personInfo.getDetailAddress())) {
            if (StringUtils.isNotBlank(personInfo.getAddress())) {
                String detailAddress = String.format("%s%s%s%s%s%s", StrUtil.formatStr(personInfo.getProvince()),
                        StrUtil.formatStr(personInfo.getCity()),
                        StrUtil.formatStr(personInfo.getDistrict()),
                        StrUtil.formatStr(personInfo.getCounty()),
                        StrUtil.formatStr(personInfo.getCommunity()),
                        StrUtil.formatStr(personInfo.getAddress()));
                personInfo.setDetailAddress(detailAddress);
                personInfoService.updateIgnoreNull(personInfo);
            }
        }
        Cnd cnd = Cnd.NEW();
        SqlExpressionGroup criSql = cnd.where();
        criSql.andEquals("param_data->>'personId'", personInfo.getId())
                .andEquals(Sqfw_formSummary_new::getType, personInfo.getBusinessType());
        // 获取最新的一条数据
        cnd.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        cnd.limit(1);
        Sqfw_formSummary_new summaryNew = sqfwFormsummaryNewService.fetch(cnd);
        if (summaryNew != null) {
            personInfo.setParamData(summaryNew.getParamData());
        }
    }
}
